package com.unisyou.handler;

import com.unisyou.bean.WXUsersBean;
import com.unisyou.config.PropertiesConfig;
import com.unisyou.utils.HttpClient;
import com.unisyou.utils.JSONUtils;
import com.unisyou.utils.SignDecode;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 取消关注处理器
 */
@Component
public class UnsubscribeHandler extends AbstractHandler {

    @Autowired
    private PropertiesConfig propertiesConfig;
    @Autowired
    private HttpClient httpClient;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager)throws WxErrorException {
        String openId = wxMessage.getFromUser();
        WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMessage.getFromUser(), null);
        if(!StringUtils.isBlank(openId)){
            String url = propertiesConfig.getUrl()+propertiesConfig.getSaveWxUserInfoPath();
            WXUsersBean wxUsersBean = WXUsersBean.transfer(userWxInfo);
            String beanToJSONString = JSONUtils.beanToJson(wxUsersBean);
            Map<String,Object> paramsMap = SignDecode.getInstance().encode(beanToJSONString);
            paramsMap.put("token","");
            Map<String,Object> resultMap = httpClient.clientForPostBody(url,paramsMap);
            if(!"0".equals(resultMap.get("resultCode").toString())){
                this.logger.info("取消关注修改用户信息失败:{}",resultMap.get("resultMsg").toString());
            }
        }
        return null;
    }

}
